<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;

use app\lib\baidu\Api as baiduApi;
require_once '../extend/baidu.bos/BaiduBce.phar';
// use BaiduBce\BceClientConfigOptions;
// use BaiduBce\Util\MimeTypes;
// use BaiduBce\Http\HttpHeaders;
// use BaiduBce\Services\Bos\BosClient;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\Http\BceHttpClient;


class Plan extends Controller
{
    public function imageImport(){
        // $bos_config = config('config.baidu_bos');
        // $list = Db::name('image')->select();
        // foreach ($list as $k => $vo) {
        //     if (empty($vo['image'])) {
        //         Db::name('image')->where('id',$vo['id'])->update(['image'=>$bos_config['bos_url'].'/'.$vo['name']]);
        //     }
            
        // }
        // dump($list);die;
        $curtime = time();
        $list = Db::name('image_import')->where('status',0)->select();
        foreach ($list as $k => $vo) {
            if (time() - $curtime > 55) {
              exit();
            }
            $bos_config = config('config.baidu_bos');
            $configs = array(
                'credentials' => array(
                    'ak' => $bos_config['credentials']['accessKeyId'],
                    'sk' => $bos_config['credentials']['secretAccessKey'],
                ),
                'endpoint' => $bos_config['bos_url'],
            );

            $body = '';
            $params = json_decode('{"delimiter":"","marker":"","maxKeys":"","prefix":"'.$vo['bos_path'].'"}',true);
            $headers = array( 
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            );

            try{
              $response = (new BceHttpClient())->sendRequest(
                $configs,'GET',"/",
                $body,
                $headers,
                $params,
                new BceV1Signer()
              );
              $result = $response["body"];
              $result = json_decode($result,true);
              $objects = $result['contents'];
              // dump($objects);die;
              // <=1 是因为目录也算
              if (count($objects) <= 1) {
                  Db::name('image_import')->where('id',$vo['id'])->update([
                    'status'=>-1,
                    'remark'=>'目录没有文件',
                    'utime'=>time()
                  ]);
              }elseif($vo['total'] == 0){
                  Db::name('image_import')->where('id',$vo['id'])->update([
                    'total'=>count($objects) - 1
                  ]);
              }

              foreach ($objects as $o_k => $o_v) {
                  if (time() - $curtime > 55) {
                    exit();
                  }
                  if ($o_k <= $vo['num']) {
                      continue;
                  }
                  $image = $bos_config['bos_url'].'/'.$o_v['key'];
                  $info = file_get_contents($image.'?x-bce-process=image/info');
                  $info = json_decode($info,true);
                  if (!empty($info)) {
                    if ($info['imageWidth']['value'] != $info['imageHeight']['value']) {
                      Db::name('import_log')->insert([
                        'image_import_id'=>$vo['id'],
                        'name'=>$o_v['key'],
                        'ctime'=>time(),
                        'remark'=>'图片尺寸不符',
                        'status'=>-1
                      ]);
                      continue;
                    }
                  }

                  $params = [];
                  $tags = '';
                  $result = (new baiduApi())->imageUpload($image,json_encode($params,JSON_UNESCAPED_UNICODE),$tags);

                  $save_data = [
                    'name'=>$o_v['key'],
                    'image'=>$image,
                    'brief'=>json_encode($params,JSON_UNESCAPED_UNICODE),
                    'tags'=>$tags,
                    'ctime'=>time()
                  ];
                  $save_data['extension'] = explode('.',$save_data['name']);
                  $save_data['extension'] = $save_data['extension'][count($save_data['extension']) - 1];
                  if ($result['status'] == 0) {
                    $save_data['status'] = -1;
                    $save_data['remark'] = $result['msg'];
                  }else{
                    $save_data['status'] = 1;
                    $save_data['cont_sign'] = $result['cont_sign'];
                  }
                  Db::name('image')->insert($save_data);

                  Db::name('image_import')->where('id',$vo['id'])->update([
                    'num'=>$o_k
                  ]);
              }

            }catch(Exception $e) {
              echo $e->getMessage();
            }
            
            if ($o_k == count($objects) - 1) {
                Db::name('image_import')->where('id',$vo['id'])->update([
                    'status'=>1,
                    'utime'=>time()
                ]);
            }            
        }
        echo 'success';
    }






   
}
